package com.gk.panda.apis.dahua.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gk.panda.apis.dahua.dahuasdk.demo.frame.vto.DefaultDisConnect;
import com.gk.panda.apis.dahua.dahuasdk.demo.frame.vto.DefaultHaveReconnect;
import com.gk.panda.apis.dahua.dahuasdk.demo.module.LoginModule;
import com.gk.panda.apis.dahua.dahuasdk.lib.NetSDKLib;
import com.gk.panda.apis.dahua.dahuasdk.lib.NetSDKLib.LLong;
import com.gk.panda.apis.dahua.dahuasdk.lib.ToolKits;
import com.gk.panda.apis.dahua.dahuasdk.lib.Utils;
import com.gk.panda.apis.dahua.dahuasdk.lib.structure.NET_ATTRIBUTE_INFO;
import com.gk.panda.apis.dahua.dahuasdk.lib.structure.NET_GET_CONDITION_INFO;
import com.gk.panda.apis.dahua.dahuasdk.lib.structure.NET_IN_SCADA_GET_ATTRIBUTE_INFO;
import com.gk.panda.apis.dahua.dahuasdk.lib.structure.NET_OUT_SCADA_GET_ATTRIBUTE_INFO;
import com.gk.panda.apis.enums.DeviceManagerModelTypeEnum;
import com.gk.panda.apis.service.DeviceEnvMonitorService;
import com.gk.panda.apis.service.DeviceManagerService;
import com.gk.panda.apis.service.DeviceService;
import com.gk.panda.apis.task.DahuaDataTask;
import com.gk.panda.commons.constant.Constants;
import com.gk.panda.pojo.DeviceEntity;
import com.gk.panda.pojo.DeviceEnvMonitorEntity;
import com.gk.panda.pojo.DeviceManager;
import com.sun.jna.Memory;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.gk.panda.apis.dahua.dahuasdk.demo.module.LoginModule.netsdk;

/**
 * @Description 大华设备业务逻辑
 * @Author zhangguoqiao
 * @Date 2022/12/13 02:16
 * @Version 1.0
 */
//@Component
@Slf4j
public class SCADADemoHD implements InitializingBean {

    // 句柄+设备
    private static final JSONObject deviceJson = new JSONObject();
    // 设备列表
    private static final List<DahuaDevice> loginDeviceList = new ArrayList<>();
    // 时间格式
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat hour = new SimpleDateFormat("yyyy-MM-dd HH");
    // 排除不需要保存的项
    private static String[] excludeArray = {"CPU利用率", "内存利用率", "经度", "纬度"};
    private static final List<String> excludes = Arrays.asList(excludeArray);

    private static Map<LLong, Map<String, NetSDKLib.NET_SCADA_NOTIFY_POINT_INFO>> cacheMap = new HashMap<>();

    private static Map<LLong, DeviceEnvMonitorEntity> cacheEnvMap = new HashMap<>();

    private static List<DahuaDevice> loginFailedList = new ArrayList<>();

    @Autowired
    private DeviceEnvMonitorService deviceEnvMonitorService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private DeviceManagerService deviceManagerService;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 查询动环设备
        List<DeviceEntity> dhList = deviceService.list(Wrappers.<DeviceEntity>lambdaQuery().eq(DeviceEntity::getDelFlag, 0));
        if (CollectionUtils.isEmpty(dhList)) {
            return;
        }
        // 去设备管理里面查询ip对应的基础信息
        List<String> ips = new ArrayList<>(dhList.size());
        dhList.forEach(k -> ips.add(k.getIp()));
        List<DeviceManager> deviceManagers = deviceManagerService.list(Wrappers.<DeviceManager>lambdaQuery()
                .eq(DeviceManager::getDelFlag, Constants.ZERO)
//                .eq(DeviceManager::getDeviceStatus,0)
                .eq(DeviceManager::getModelType, DeviceManagerModelTypeEnum.ECOLOGICAL_EQUIPMENT.getCode())
                .in(DeviceManager::getDeviceIp, ips));
        for (DeviceEntity device : dhList) {
            DahuaDevice dahuaDevice = new DahuaDevice();
            deviceManagers.forEach(v -> {
                if (device.getIp().equals(v.getDeviceIp())) {
                    BeanUtils.copyProperties(v, dahuaDevice);
                }
            });
            dahuaDevice.setConnect(false);
            dahuaDevice.setDevice(device);
            loginDeviceList.add(dahuaDevice);
        }
        DefaultDisConnect.GetInstance().setScadaDemoHD(this);
        DefaultHaveReconnect.getINSTANCE().setScadaDemoHD(this);
        // sdk初始化
        LoginModule.init(DefaultDisConnect.GetInstance(), DefaultHaveReconnect.getINSTANCE());

        // 设备启动
        deviceRun();
    }

    public void deviceRun() {
        log.info("-------大华设备启动-------");
        for (DahuaDevice device : loginDeviceList) {
            DeviceEntity deviceInfo = device.getDevice();
            //登录
            LLong m_hLoginHandle = LoginModule.login(deviceInfo.getIp(), deviceInfo.getPort(), deviceInfo.getAccount(), deviceInfo.getPassword());
            if (m_hLoginHandle != null && !"0".equals(m_hLoginHandle.toString())) {
                //缓存句柄和设备
                device.setConnect(true);
                deviceJson.put(m_hLoginHandle.toString(), device);
                //初始化监测信息map
                cacheMap.put(m_hLoginHandle, new HashMap<>());
                cacheEnvMap.put(m_hLoginHandle, new DeviceEnvMonitorEntity());
                log.info("设备：" + deviceInfo.getIp() + "设备运行!------句柄：" + m_hLoginHandle);
                // 获取实时信息
                scadaAttachInfo(m_hLoginHandle);
            } else {
                loginFailedList.add(device);
            }
//            // 测试登出
//            Thread.sleep(20000);
//            logout(m_hLoginHandle);

        }
    }

    /**
     * 设备重连回调方法
     */
    public void reconnectRun(LLong lLoginID) {
        log.info("-------大华设备重连-------");
        if (deviceJson.get(lLoginID.toString()) != null) {
            log.info("-------句柄存在-------");
            DahuaDevice device = deviceJson.getObject(lLoginID.toString(), DahuaDevice.class);
            if (!device.isConnect()) {
                // 获取实时信息
                scadaAttachInfo(lLoginID);
                // 缓存句柄和设备
                device.setConnect(true);
                deviceJson.put(lLoginID.toString(), device);
            }
        } else {
            log.info("-------句柄不存在-------");
            for (String key : deviceJson.keySet()) {
                DahuaDevice device = deviceJson.getObject(key, DahuaDevice.class);
                if (!device.isConnect()) {
                    DeviceEntity deviceInfo = device.getDevice();
                    // 登录
                    LLong m_hLoginHandle = LoginModule.login(deviceInfo.getIp(), deviceInfo.getPort(), deviceInfo.getAccount(), deviceInfo.getPassword());
                    // 初始化监测信息map
                    cacheMap.put(m_hLoginHandle, new HashMap<>());
                    cacheEnvMap.put(m_hLoginHandle, new DeviceEnvMonitorEntity());
                    log.info("设备：" + deviceInfo.getIp() + "设备运行!------句柄：" + m_hLoginHandle);
                    scadaAttachInfo(m_hLoginHandle);
                    // 缓存句柄和设备
                    device.setConnect(true);
                    deviceJson.put(m_hLoginHandle.toString(), device);
                    log.info("ip：{}isConnect已设为：{}", deviceInfo.getIp(), device.isConnect());
                }
            }
        }
    }


    /**
     * 设备断开回调方法
     *
     * @param lLoginID
     */
    public void disConnectRun(LLong lLoginID) {
        log.info("-------大华设备已断连-------");
        DahuaDevice device = deviceJson.getObject(lLoginID.toString(), DahuaDevice.class);
        device.setConnect(false);
        deviceJson.put(lLoginID.toString(), device);
        log.info("ip：{}isConnect已设为：{}", device.getDevice().getIp(), device.isConnect());
    }

    /**
     * 登出
     */
    public static void logout(LLong m_hLoginHandle) {
        log.info("-------开始登出-------");
        if (LoginModule.logout(m_hLoginHandle)) {
            log.info(m_hLoginHandle + "：登出成功！");
        }
    }

    /**
     * 获取当前主机接入的外部设备ID
     */
    Vector<String> deviceIds = new Vector<String>();
    // 多平台 编码
    private final static Charset encode = Charset.forName(Utils.getPlatformEncode());

    public boolean getDeviceIdList(LLong m_hLoginHandle) {
        deviceIds.clear();

        // model.setColumnCount(0);
        int nCount = 64; //

        NetSDKLib.NET_SCADA_DEVICE_ID_INFO[] stuDeviceIDList = new NetSDKLib.NET_SCADA_DEVICE_ID_INFO[nCount];
        for (int i = 0; i < stuDeviceIDList.length; ++i) {
            stuDeviceIDList[i] = new NetSDKLib.NET_SCADA_DEVICE_ID_INFO();
        }

        NetSDKLib.NET_SCADA_DEVICE_LIST stuSCADADeviceInfo = new NetSDKLib.NET_SCADA_DEVICE_LIST();
        stuSCADADeviceInfo.nMax = nCount;
        int nSize = stuDeviceIDList[0].size() * nCount;
        stuSCADADeviceInfo.pstuDeviceIDInfo = new Memory(nSize);   // 监测设备信息
        stuSCADADeviceInfo.pstuDeviceIDInfo.clear(nSize);
        ToolKits.SetStructArrToPointerData(stuDeviceIDList, stuSCADADeviceInfo.pstuDeviceIDInfo);
        if (queryDevState(NetSDKLib.NET_DEVSTATE_SCADA_DEVICE_LIST, stuSCADADeviceInfo, m_hLoginHandle)) {
            return false;
        }
        if (stuSCADADeviceInfo.nRet == 0) {
            // 外部设备没有有效ID
            log.info("当前主机接入的外部设备ID有效个数为0");
            return false;
        }
        // 从 Pointer 提取数据
        ToolKits.GetPointerDataToStructArr(stuSCADADeviceInfo.pstuDeviceIDInfo, stuDeviceIDList);
        // 打印数据并更新设备ID
        log.info("获取当前主机接入的外部设备ID的有效个数：" + stuSCADADeviceInfo.nRet);
        for (int i = 0; i < stuSCADADeviceInfo.nRet; ++i) {
            String deviceID = "";
            String deviceName = "";
            deviceName = new String(stuDeviceIDList[i].szDevName, encode).trim();
            deviceID = new String(stuDeviceIDList[i].szDeviceID, encode).trim();
            log.info("外部设备{} 设备id{} 设备名称{}", i, new String(stuDeviceIDList[i].szDeviceID, encode).trim(), deviceName);
            deviceIds.add(deviceID);
        }
        return true;
    }

    /**
     * 查询设备状态
     */
    public boolean queryDevState(int nType, NetSDKLib.SdkStructure stuInfo, LLong m_hLoginHandle) {

        IntByReference intRetLen = new IntByReference();
        stuInfo.write();
        if (!netsdk.CLIENT_QueryDevState(m_hLoginHandle, nType, stuInfo.getPointer(), stuInfo.size(), intRetLen, 3000)) {
            return true;
        }
        stuInfo.read();
        return false;
    }


    /**
     * 取消订阅监测点位报警信息
     */
    public void scadaAlarmDetachInfo() {
        if (alarmAttachInfoHandle.longValue() != 0) {
            netsdk.CLIENT_SCADAAlarmDetachInfo(alarmAttachInfoHandle);
            alarmAttachInfoHandle.setValue(0);
        }
    }

    // 监测点位信息，订阅句柄
    private static NetSDKLib.LLong attachInfoHandle = new NetSDKLib.LLong(0);
    // 监测点位报警，订阅句柄
    private NetSDKLib.LLong alarmAttachInfoHandle = new NetSDKLib.LLong(0);

    /**
     * 普通报警监听回调
     */
    private static class MessCallback implements NetSDKLib.fMessCallBack {
        private static MessCallback INSTANCE;

        @Override
        public boolean invoke(int lCommand, NetSDKLib.LLong lLoginID, Pointer pStuEvent,
                              int dwBufLen, String strDeviceIP, NativeLong nDevicePort,
                              Pointer dwUser) {
            switch (lCommand) {
                case NetSDKLib.NET_ALARM_SCADA_DEV_ALARM: {  // 12706 检测采集设备报警事件   "SCADADevAlarm"

                    NetSDKLib.ALARM_SCADA_DEV_INFO msg = new NetSDKLib.ALARM_SCADA_DEV_INFO();
                    ToolKits.GetPointerData(pStuEvent, msg);
                    String deviceId = new String(msg.szDevID, encode).trim();
                    /*System.out.println("[检测采集设备报警事件] nChannel :" + msg.nChannel);
                    System.out.println("设备ID :" + deviceId);
                    String description = new String(msg.szDesc, encode).trim();
                    String deviceName = new String(msg.szDevName, encode).trim();
                    System.out.println(" nAction :" + msg.nAction +
                            " nAlarmFlag :" + msg.nAlarmFlag + "\n" + "故障设备名称" + deviceName
                            + "\n" + "描述" + description + "时间" + msg.stuTime);*/
                    break;
                }
                default:
                    // System.out.println("What's lCommand: " + lCommand);
                    break;
            }
            return true;
        }
    }

    /**
     * 订阅监测点位实时信息
     */
    public void scadaAttachInfo(LLong m_hLoginHandle) {
        // 入参
        NetSDKLib.NET_IN_SCADA_ATTACH_INFO stIn = new NetSDKLib.NET_IN_SCADA_ATTACH_INFO();
        stIn.cbCallBack = SCADAAttachInfoCallBackHD.getInstance();
        // 出参
        NetSDKLib.NET_OUT_SCADA_ATTACH_INFO stOut = new NetSDKLib.NET_OUT_SCADA_ATTACH_INFO();
        attachInfoHandle = netsdk.CLIENT_SCADAAttachInfo(m_hLoginHandle, stIn, stOut, 3000);
        if (attachInfoHandle.longValue() != 0) {
            log.info("CLIENT_SCADAAttachInfo: 订阅监测点位实时信息成功！");
        }
    }


    /**
     * 获取设备点位信息
     */
    public void getDeviceAttribute(LLong m_hLoginHandle) throws UnsupportedEncodingException {
        Map<Integer, String> num2PointType = new HashMap<Integer, String>(6);
        num2PointType.put(0, "UNKNOWN");
        num2PointType.put(1, "ALL");
        num2PointType.put(2, "YC");
        num2PointType.put(3, "YX");
        num2PointType.put(4, "YT");
        num2PointType.put(5, "YK");
        for (int i = 0; i < deviceIds.size(); i++) {
            String deviceId = deviceIds.get(i);
            int nMaxAttributeInfoNum = 20;
            // 获取设备点位信息 入参
            NET_IN_SCADA_GET_ATTRIBUTE_INFO inParam = new NET_IN_SCADA_GET_ATTRIBUTE_INFO();
            // 获取设备点位信息 出参
            NET_OUT_SCADA_GET_ATTRIBUTE_INFO outParam = new NET_OUT_SCADA_GET_ATTRIBUTE_INFO();
            // 获取条件
            NET_GET_CONDITION_INFO conditionInfo = new NET_GET_CONDITION_INFO();
            conditionInfo.szDeviceID = deviceIds.get(i).getBytes();
            conditionInfo.bIsSendID = 1;
            outParam.nMaxAttributeInfoNum = nMaxAttributeInfoNum;
            // 设备点位信息(内存由用户申请)
            NET_ATTRIBUTE_INFO attributeInfo = new NET_ATTRIBUTE_INFO();

            outParam.pstuAttributeInfo = new Memory(nMaxAttributeInfoNum * attributeInfo.size());
            inParam.stuCondition = conditionInfo;
            inParam.write();
            outParam.write();
            boolean ret = netsdk.CLIENT_SCADAGetAttributeInfo(m_hLoginHandle, inParam.getPointer(), outParam.getPointer(), 3000);
            inParam.read();
            outParam.read();

            if (ret) {
                log.info("SCADAGetAttributeInfo succeed!");
                outParam.read();
                int retAttributeInfoNum = outParam.nRetAttributeInfoNum;
                NET_ATTRIBUTE_INFO infos[] = new NET_ATTRIBUTE_INFO[retAttributeInfoNum];
                for (int j = 0; j < retAttributeInfoNum; j++) {
                    infos[j] = new NET_ATTRIBUTE_INFO();
                }
                log.info("infos 大小： " + infos.length);
                ToolKits.GetPointerDataToStructArr(outParam.pstuAttributeInfo, infos);
                for (int n = 0; n < retAttributeInfoNum; n++) {
                    NET_ATTRIBUTE_INFO out = new NET_ATTRIBUTE_INFO();
                    out = infos[n];
                    log.info("设备ID：" + deviceId + "点位类型: " + num2PointType.get(out.emPointType)
                            + "点位名称: " + new String(out.szSignalName, encode).trim() + "时延: " + out.nDelay);
                }
            }
        }


    }

    /**
     * 取消订阅监测点位实时信息
     */
    public void scadaDetachInfo() {
        if (attachInfoHandle.longValue() != 0) {
            netsdk.CLIENT_SCADADetachInfo(attachInfoHandle);
            attachInfoHandle.setValue(0);
            log.info("CLIENT_SCADADetachInfo: 取消订阅监测点位实时信息成功！");
        }
    }


    /**
     * 订阅监测点位信息回调
     */
    private static class SCADAAttachInfoCallBackHD implements NetSDKLib.fSCADAAttachInfoCallBack {
        private static SCADAAttachInfoCallBackHD INSTANCE;

        private SCADAAttachInfoCallBackHD() {
        }

        public static final SCADAAttachInfoCallBackHD getInstance() {
            if (INSTANCE == null) {
                INSTANCE = new SCADAAttachInfoCallBackHD();
            }
            return INSTANCE;
        }

        @Override
        public void invoke(LLong lLoginID, LLong lAttachHandle, NetSDKLib.NET_SCADA_NOTIFY_POINT_INFO_LIST pInfo, int nBufLen, Pointer dwUser) {
            if (DahuaDataTask.getDataEnable) {
                for (int i = 0; i < pInfo.nList; i++) {
                    cacheEnvInfo(lLoginID, pInfo.stuList[i]);
                }
            }
        }
    }


    private static void cacheEnvInfo(LLong lLoginID, NetSDKLib.NET_SCADA_NOTIFY_POINT_INFO stuInfo) {
        cacheEnvMap.computeIfAbsent(lLoginID, k -> new DeviceEnvMonitorEntity());
        String szPointName = new String(stuInfo.szPointName, encode).trim();
        // 过滤不需要保存的项，点位名
        if (StringUtils.isBlank(szPointName) || excludes.contains(szPointName)) {
            return;
        }
        if (ObjectUtils.isEmpty(cacheEnvMap.get(lLoginID).getDeviceId())) {
            DahuaDevice device = deviceJson.getObject(lLoginID.toString(), DahuaDevice.class);
            cacheEnvMap.get(lLoginID).setDeviceId(device.getDeviceId());
            cacheEnvMap.get(lLoginID).setDeviceNum(device.getDeviceSn());
            cacheEnvMap.get(lLoginID).setDeviceName(device.getDeviceName());
            cacheEnvMap.get(lLoginID).setAddress(device.getDeviceAddress());
            cacheEnvMap.get(lLoginID).setOrgId(device.getFkOrgId());
            cacheEnvMap.get(lLoginID).setOrgName(device.getOrgName());
            cacheEnvMap.get(lLoginID).setLot(device.getLongitude());
            cacheEnvMap.get(lLoginID).setLat(device.getLatitude());
        }
        if ("温度".equals(szPointName)) {
            cacheEnvMap.get(lLoginID).setTemperature(String.valueOf(stuInfo.fValue));
        } else if ("湿度".equals(szPointName)) {
            cacheEnvMap.get(lLoginID).setHumidity(String.valueOf(stuInfo.fValue));
        } else if ("噪声".equals(szPointName)) {
            cacheEnvMap.get(lLoginID).setNoise(String.valueOf(stuInfo.fValue));
        } else if ("气压".equals(szPointName)) {
            cacheEnvMap.get(lLoginID).setPressure(String.valueOf(stuInfo.fValue));
        } else if ("风速".equals(szPointName)) {
            cacheEnvMap.get(lLoginID).setWindSpeed(String.valueOf(stuInfo.fValue));
        } else if ("风向".equals(szPointName)) {
            cacheEnvMap.get(lLoginID).setWindDirection(String.valueOf(stuInfo.fValue));
        } else if ("PM2.5".equals(szPointName)) {
            cacheEnvMap.get(lLoginID).setPm25(String.valueOf(stuInfo.fValue));
        } else if ("PM10".equals(szPointName)) {
            cacheEnvMap.get(lLoginID).setPm10(String.valueOf(stuInfo.fValue));
        }
        if (StringUtils.isBlank(cacheEnvMap.get(lLoginID).getCreateName())) {
            cacheEnvMap.get(lLoginID).setCreateName("panda@cd");
        }
        try {
            if (StringUtils.isBlank(cacheEnvMap.get(lLoginID).getMonitorTime())) {
                String format = hour.format(new Date());
                cacheEnvMap.get(lLoginID).setMonitorTime(format);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveEnvToDataBase() {
        Date date = new Date();
        log.info(sdf.format(date) + "-保存数据到数据库！！！");
        List<DeviceEnvMonitorEntity> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(cacheEnvMap.values())) {
            for (DeviceEnvMonitorEntity data : cacheEnvMap.values()) {
                if (data != null) {
                    data.setCreateTime(date);
                    list.add(data);
                }
            }
            deviceEnvMonitorService.saveBatch(list);
            List<Integer> deviceIds = list.stream().map(DeviceEnvMonitorEntity::getDeviceId).collect(Collectors.toList());
            List<DeviceManager> deviceManagers = deviceManagerService.list(Wrappers.<DeviceManager>lambdaQuery()
                    .eq(DeviceManager::getDelFlag, Constants.ZERO)
                    .eq(DeviceManager::getModelType, DeviceManagerModelTypeEnum.ECOLOGICAL_EQUIPMENT.getCode()));
            for (DeviceManager deviceManager : deviceManagers) {
                if (!deviceIds.contains(deviceManager.getDeviceId())) {
                    deviceManagerService.update(Wrappers.<DeviceManager>lambdaUpdate()
                            .set(DeviceManager::getDeviceStatus, Constants.ONE)
                            .eq(DeviceManager::getDeviceId, deviceManager.getDeviceId()));
                } else {
                    deviceManagerService.update(Wrappers.<DeviceManager>lambdaUpdate()
                            .set(DeviceManager::getDeviceStatus, Constants.ZERO)
                            .eq(DeviceManager::getDeviceId, deviceManager.getDeviceId()));
                }
            }
        }
        cacheEnvMap.clear();
    }

    /**
     * 项目启动时未登录成功设备重新登录
     */
    public void loginAgain() {
//        List<DeviceManager> deviceManagers = deviceManagerService.list(Wrappers.<DeviceManager>lambdaQuery()
//                .eq(DeviceManager::getDelFlag, Constants.ZERO)
//                .eq(DeviceManager::getDeviceStatus, Constants.ONE)
//                .eq(DeviceManager::getModelType, DeviceManagerModelTypeEnum.ECOLOGICAL_EQUIPMENT.getCode()));
//        if (CollectionUtils.isEmpty(deviceManagers)) return;
//        for (DeviceManager deviceManager : deviceManagers) {
//            DeviceEntity device = deviceService.getOne(Wrappers.<DeviceEntity>lambdaQuery().eq(DeviceEntity::getIp, deviceManager.getDeviceIp()));
//            DahuaDevice dahuaDevice = new DahuaDevice();
//            BeanUtils.copyProperties(deviceManager, dahuaDevice);
//            dahuaDevice.setConnect(false);
//            dahuaDevice.setDevice(device);
        if (CollectionUtils.isEmpty(loginFailedList)) return;
        loginFailedList.forEach(dahuaDevice -> {
            DeviceEntity device = dahuaDevice.getDevice();
            //登录
            LLong m_hLoginHandle = LoginModule.login(device.getIp(), device.getPort(), device.getAccount(), device.getPassword());
            if (m_hLoginHandle != null && !"0".equals(m_hLoginHandle.toString())) {
                //缓存句柄和设备
                dahuaDevice.setConnect(true);
                deviceJson.put(m_hLoginHandle.toString(), device);
                //初始化监测信息map
                cacheMap.put(m_hLoginHandle, new HashMap<>());
                cacheEnvMap.put(m_hLoginHandle, new DeviceEnvMonitorEntity());
                log.info("设备：" + device.getIp() + "设备运行!------句柄：" + m_hLoginHandle);
                // 获取实时信息
                scadaAttachInfo(m_hLoginHandle);
                loginFailedList.remove(dahuaDevice);
            }
        });
    }

}
